package java_thinking.unit_17._17_9_10;

import java_thinking.unit_17._17_2_6.Countries;

import java.util.*;

/**
 * @Desc:   案例：用一对ArrayList实现了一个Map
 * @author: cww
 * @DateTime: 2019/4/18 8:42
 */

public class SlowMap<K,V> extends AbstractMap<K,V> {
    private List<K> keys = new ArrayList<>();
    private List<V> values = new ArrayList<>();
    public V put(K key,V value) {
        V oldValue = get(key);
        if (!keys.contains(key)) {
            keys.add(key);
            values.add(value);
        } else {
            values.set(keys.indexOf(key),value);
        }
        return oldValue;
    }

    /**
     * 注意这里的key是Object而不是K，这是泛型加在jdk中出现的太晚的原因
     * @param key
     * @return
     */
    public V get(Object key) {
        if (!keys.contains(key)) {
            return null;
        }
        return values.get(keys.indexOf(key));
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        Set<Map.Entry<K,V>> set = new HashSet<>();
        Iterator<K> ki = keys.iterator();
        Iterator<V> kv = values.iterator();
        while (ki.hasNext()) {
            set.add(new MapEntry<K,V>(ki.next(),kv.next()));
        }
        return set;
    }
    public static class MapEntry<K,V> implements Map.Entry<K,V> {

        private K key;
        private V value;

        public MapEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public K getKey() {
            return key;
        }

        @Override
        public V getValue() {
            return value;
        }

        @Override
        public V setValue(V value) {
            return null;
        }

        @Override
        public int hashCode() {
            return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
        }

        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof  MapEntry)) return false;
            MapEntry mapEntry = (MapEntry)obj;
            return (key == null ? mapEntry.getKey() == null : key.equals(mapEntry.getKey()))
                    && (value == null ? mapEntry.getValue() == null : value.equals(mapEntry.getValue()));
        }

        @Override
        public String toString() {
            return key + " = " + value;
        }
    }

    public static void main(String[] args) {
        SlowMap<String,String> map = new SlowMap<>();
        map.putAll(Countries.capitals(15));
        System.out.println(map);
        System.out.println(map.get("CAMEROON"));
        System.out.println(map.entrySet());
    }
}
